<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link      http://cakephp.org CakePHP(tm) Project
 * @since     0.2.9
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace App\Controller;

use Cake\Core\Configure;
use Cake\Event\Event;
use Cake\Network\Exception\ForbiddenException;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\Datasource\ConnectionManager;

/**
 * Static content controller
 *
 * This controller will render views from Template/Pages/
 * @property \App\Model\Table\JobsTable $Jobs
 * @property \App\Model\Table\ProvincesTable $Provinces
 * @property \App\Model\Table\CitiesTable $Cities
 * @property \App\Model\Table\SchoolsTable $Schools
 * @property \App\Model\Table\CategoriesTable $Categories
 * @property \App\Model\Table\RecruitsTable $Recruits
 * @property \App\Model\Table\RecruitsTable $SiteTdk
 * @method \App\Model\Entity\Job[] paginate($object = null, array $settings = [])
 */
class IndexController extends AppController
{


    public function beforeFilter(Event $event)
    {
        $this->loadModel('Jobs');
        $this->loadModel('Provinces');
        $this->loadModel('Cities');
        $this->loadModel('Schools');
        $this->loadModel('Categories');
        $this->loadModel('Recruits');
        $this->loadModel('SiteTdk');

        /**
         * 设置 cookies
         */
        if(!array_key_exists('city',$_COOKIE)){
            $_COOKIE['city'] = '全国';
        }

        return parent::beforeFilter($event);
    }

    /**
     * Displays a view
     *
     * @return void|\Cake\Network\Response
     * @throws \Cake\Network\Exception\ForbiddenException When a directory traversal attempt.
     * @throws \Cake\Network\Exception\NotFoundException When the view file could not
     *   be found or \Cake\View\Exception\MissingTemplateException in debug mode.
     */
    public function index(){

        $res = $this->SiteTdk->gettdk('index');
        $this->set('title',$res['title']);
        $this->set('keywords',$res['keywords']);
        $this->set('description',$res['description']);

        /**
         * 首页显示数据
         * 显示6个分类
         * 1,幼儿园
         * 2,小学
         * 3,初中
         * 4,高中
         * 5,语言
         * 6,特长
         */

        if($_COOKIE['city'] !== '全国') {
            $baby = $this->filterContentByCate(1,$this->getCityIds());
            $primarySchool = $this->filterContentByCate(2,$this->getCityIds());
            $juniorHighSchool = $this->filterContentByCate(3,$this->getCityIds());
            $seniorHighSchool = $this->filterContentByCate(4,$this->getCityIds());
            $language = $this->filterContentByCate(5,$this->getCityIds());
            $strongPoint = $this->filterContentByCate(6,$this->getCityIds());
            // 最新招聘信息
            $latestNews = $this->Recruits->find()->where(['city_id in'=>$this->getCityIds()])->limit(5)->orderDesc('publish_date');
            // 测试用
            $latestNews_bottom = $this->Recruits->find('all', array('order' => ' RAND()'))->where(["id in"=>[50120,50121,50122,50123,50124,50125,50126,50127,50128,50129,50130,50131,50132,50133,50134,50135,50136,50137,50138,50139,50140,50141,50142,50143,50144,50145,50146,50147,50148,50149,50150,50151,50152,50153,50154,50155,50156,50157,50158,50159,50160,50161,50162,50163,50164,50165,50166,50167,50168,50169,50170,50171,50172,50173,50174,50175,50176,50177,50178,50179,50180,50181,50182,50183,50184,50185,50186,50187,50188,50189,50190,50191,50192,50193,50194,50195,50196,50197,50198,50199,50200,50201,50202,50203,50204,50205,50206,50207,50208,50209,50210,50211,50212,50213,50214,50215,50216,50217,50218,50219]])->limit(4)->orderDesc('publish_date');
            // 最新招聘信息
            $schoolIds = $this->getSchoolIds($this->getCityIds());

            if (!$schoolIds||count($schoolIds)==0){
                $schoolIds = [-1];
            }
            $latestSchool = $this->Jobs->find()->where(['school_id in'=>$schoolIds])->contain(['Schools'])
                ->distinct('Schools.title')->orderDesc('Jobs.view_count')->limit(20);
//            var_dump($latestSchool);exit;
        } else {
            $baby = $this->filterContentByCate(1);
            $primarySchool = $this->filterContentByCate(2);
            $juniorHighSchool = $this->filterContentByCate(3);
            $seniorHighSchool = $this->filterContentByCate(4);
            $language = $this->filterContentByCate(5);
            $strongPoint = $this->filterContentByCate(6);

            $latestNews = $this->Recruits->find()->limit(5)->orderDesc('publish_date');
            // 测试用
//            $latestNews_bottom = $this->Recruits->find('all', array('order' => ' RAND()'))->where(["id in"=>[50120,50121,50122,50123,50124,50125,50126,50127,50128,50129,50130,50131,50132,50133,50134,50135,50136,50137,50138,50139,50140,50141,50142,50143,50144,50145,50146,50147,50148,50149,50150,50151,50152,50153,50154,50155,50156,50157,50158,50159,50160,50161,50162,50163,50164,50165,50166,50167,50168,50169,50170,50171,50172,50173,50174,50175,50176,50177,50178,50179,50180,50181,50182,50183,50184,50185,50186,50187,50188,50189,50190,50191,50192,50193,50194,50195,50196,50197,50198,50199,50200,50201,50202,50203,50204,50205,50206,50207,50208,50209,50210,50211,50212,50213,50214,50215,50216,50217,50218,50219]])->limit(4)->orderDesc('publish_date');
            // 最新招聘信息
            $latestSchool = $this->Jobs->find()->contain(['Schools'])->distinct('Schools.title')->orderDesc('Jobs.view_count')->limit(20);

        }


        $this->set(compact(
            'baby',
            'primarySchool',
            'juniorHighSchool',
            'seniorHighSchool',
            'language',
            // 测试用
            'latestNews_bottom',
            'strongPoint',
            'latestNews',
            'latestSchool'));
    }
    /**
     * 找工作
     */
    public function jobs(){
        $res = $this->SiteTdk->gettdk('jobs');
        $this->set('title',$res['title']);
        $this->set('keywords',$res['keywords']);
        $this->set('description',$res['description']);

//        $this->set('title','2018年最新中小学教师职位信息_教师招聘网');
//        $this->set('keywords','中小学教师职位,英语教师,物理教师,数学教师,语文教师,舞蹈教师,美术教师,化学教师');
//        $this->set('description','教师招聘网持续为您更新幼儿教师职位、中小学教师职位、及高中各科教师岗位，包括语文教师、化学教师、舞蹈教等招聘信息。');
        $page = $this->request->getParam('page',1);
        $this->paginate = [
            'limit'=>20,
            'page'=>$page
        ];


        /**
         * 检查是否选中城市
         */
        if($_COOKIE['city'] !== '全国' && $_COOKIE['city'] !== '') {
            $schoolIds = $this->getSchoolIds($this->getCityIds());

            if (!$schoolIds||count($schoolIds)==0){
                $schoolIds = [-1];
            }
            $query = $this->Jobs->find()->where(['school_id in'=>$schoolIds])->orderDesc('Jobs.publish_date')->contain(['Categories', 'Schools']);
        } else {
            $query = $this->Jobs->find()->orderDesc('Jobs.publish_date')->contain(['Categories', 'Schools']);
        }
        $jobsList = $this->paginate($query);
        $provinceList = $this->Provinces->find();
        $this->set(compact('jobsList'));
        $this->set(compact('provinceList'));
    }

    /**
     * 找学校
     */
    public function school(){
        $res = $this->SiteTdk->gettdk('school');
        $this->set('title',$res['title']);
        $this->set('keywords',$res['keywords']);
        $this->set('description',$res['description']);

//        $this->set('title','学校及教育机构信息_教师招聘网');
//        $this->set('keywords','公办学校招聘,私立学校招聘,培训机构招聘,教育机构招聘,知名学校招聘');
//        $this->set('description','公办学校招聘,私立学校招聘,培训机构招聘,教育机构招聘,知名学校招聘');
        $page = $this->request->getParam('page',1);
        $this->paginate = [
            'limit'=>20,
            'page'=>$page
        ];
        if($_COOKIE['city'] !== '全国' && $_COOKIE['city'] !== '') {
            $query = $this->Schools->find()->where(['city_id in'=>$this->getCityIds()])->contain(['Jobs','Cities']);
        } else {
            $query = $this->Schools->find()->contain(['Jobs','Cities']);
        }

        $schoolsList = $this->paginate($query);
        $jobCate = $this->getJobCateBySchool($schoolsList);//获取当前学校下的所有的工作的分类
        $weekHotSchool = $this->Schools->find()->contain(['Jobs','Cities'])->orderDesc('Schools.create_time')->limit(5);
        $hotWeekJobCate = $this->getJobCateBySchool($weekHotSchool);//获取当前热门学校下的分类

        $this->set(compact('schoolsList'));
        $this->set(compact('weekHotSchool'));
        $this->set(compact('jobCate'));
        $this->set(compact('hotWeekJobCate'));
    }

    /**
     * 招聘考试
     */
    public function zp(){
        $res = $this->SiteTdk->gettdk('zp');
        $this->set('title',$res['title']);
        $this->set('keywords',$res['keywords']);
        $this->set('description',$res['description']);
//        $this->set('title','全国教师编制招聘考试信息_事业单位招聘_教师招聘网');
//        $this->set('keywords','教师编制招聘考试,事业单位招聘考试,特岗教师招聘考试,教师招聘简章');
//        $this->set('description','教师招聘网为您提供教师编制考试、事业单位招聘考试及特岗教师招聘简章等信息。');

        $page = $this->request->getParam('page',1);
        $this->paginate = [
            'limit'=>20,
            'page'=>$page
        ];
        if($_COOKIE['city'] !== "全国" && $_COOKIE['city'] !== '') {
            $query = $this->Recruits->find()->where(['city_id in'=>$this->getCityIds()])->orderDesc('Recruits.publish_date');
        } else {
            $query = $this->Recruits->find()->orderDesc('Recruits.publish_date');
        }
        $recruits = $this->paginate($query);
        $this->set(compact('recruits'));
    }

    /**
     * 找学校 关键词 搜索
     */
    public function schoolSearch(){
        $res = $this->SiteTdk->gettdk('schoolSearch');
        $this->set('title',$res['title']);
        $this->set('keywords',$res['keywords']);
        $this->set('description',$res['description']);

//        $this->set('title','找学校 | 教师招聘');
//        $this->set('keywords','教师，教师职位，教师招聘');
//        $this->set('description','专注于教师招聘工作');

        $page = $this->request->getParam('page',1); //获取分页数据
        $searchWord = $this->request->getParam('searchWord');

        if($_COOKIE['city'] !== '全国' && $_COOKIE['city'] !== '') {
            $provinceId = $this->Provinces->find()->where(['name'=>$_COOKIE['city']]);//获取省份id
            if($provinceId->count()>0) {
                $cityIds = $this->getCurrentCityId($provinceId->first()->id); // 获取当前省份下的所有的cityId
            } else {
                $cityIds = $this->Cities->find()->where(['name'=>$_COOKIE['city']]);
                $cityIds = [$cityIds->first()->id];
            }
        } else {
            $singleCityId = $this->Cities->find()->where(['name'=>$_COOKIE['city']]); // 获取当前城市下的cityId
        }

        $this->paginate = [
            'limit'=>20,
            'page'=>$page
        ];
        if($_COOKIE['city'] !== '全国' && $_COOKIE['city'] !== '') {
            $query = $this->Schools->find()
                ->contain(['Jobs','Cities'])
                ->where(['Schools.city_id in'=>$cityIds,'Schools.title like'=>'%'.$searchWord.'%']);
        } else {
            $query = $this->Schools->find()
                ->contain(['Jobs','Cities'])
                ->where([
                    'Schools.title like'=>'%'.$searchWord.'%'
                ]);
        }

        $schoolsList = $this->paginate($query);
        $jobCate = $this->getJobCateBySchool($schoolsList);//获取当前学校工作下的分类
        $weekHotSchool = $this->Schools->find()->contain(['Jobs','Cities'])->orderDesc('Schools.create_time')->limit(5);
        $hotWeekJobCate = $this->getJobCateBySchool($weekHotSchool);//获取当前热门学校下的分类

        $this->set(compact('schoolsList'));
        $this->set(compact('provinceId'));
        $this->set(compact('weekHotSchool'));
        $this->set(compact('jobCate'));
        $this->set(compact('hotWeekJobCate'));
    }

    /**
     * 招聘信息 搜索
     */
    public function zpSearch(){
        $res = $this->SiteTdk->gettdk('zpSearch');
        $this->set('title',$res['title']);
        $this->set('keywords',$res['keywords']);
        $this->set('description',$res['description']);

//        $this->set('title','招聘考试 | 教师招聘');
//        $this->set('keywords','教师，教师职位，教师招聘');
//        $this->set('description','专注于教师招聘工作');

        $searchWord = $this->request->getParam('searchWord');//招聘信息的搜索关键词
        $page = $this->request->getParam('page',1); //获取分页数据


        if($_COOKIE['city'] !== '全国' && $_COOKIE['city'] !== '') {
            $provinceId = $this->Provinces->find()->where(['name'=>$_COOKIE['city']]);//获取省份id
            if($provinceId->count()>0) {
                $cityIds = $this->getCurrentCityId($provinceId->first()->id); // 获取当前省份下的所有的cityId
            } else {
                $cityIds = $this->Cities->find()->where(['name'=>$_COOKIE['city']]);
                $cityIds = [$cityIds->first()->id];
            }
        } else {
            $singleCityId = $this->Cities->find()->where(['name'=>$_COOKIE['city']]); // 获取当前城市下的cityId
        }
        $this->paginate = [
            'limit'=>20,
            'page'=>$page
        ];
        if($_COOKIE['city'] !== '全国' && $_COOKIE['city'] !== ''){
            $query = $this->Recruits
                ->find()
                ->contain(['Cities'])
                ->where(['Recruits.city_id in'=>$cityIds,'Recruits.title like '=>'%'.$searchWord.'%']);
        } else {
            $query = $this->Recruits
                ->find()
                ->contain(['Cities'])
                ->where(['Recruits.title like '=>'%'.$searchWord.'%']);
        }

        $recruits = $this->paginate($query);

        $this->set(compact('recruits'));
        $this->set(compact('provinceId'));
        $this->set(compact('singleCityId'));
    }

    /**
     * 招聘考试 detail
     */
    public function zpDetail(){

        $id = $this->request->getParam('id');
        $recruitsDetail = $this->Recruits->get($id);
        $name = $recruitsDetail->title ?$recruitsDetail->title: '招聘考试';
        $this->set('title',$name.'_教师招聘网');
        $this->set('keywords',$name);
        $this->set('description','教师招聘网为您提供教师编制考试、事业单位招聘考试及特岗教师招聘简章等信息。');
        $this->set(compact('recruitsDetail'));
    }

    /**
     * 找工作 detail
     */
    public function jobDetail(){


        $id = $this->request->getParam('id');

        $jobsDetail = $this->Jobs->get($id);// 当前岗位详细介绍
        if (!$jobsDetail){
            throw new NotFoundException(404);
        }

        $inSameSchoolJob = $this->Jobs->find()->where(['school_id'=>$jobsDetail->school_id])->contain(['Categories','Schools'])->limit(5);

        $currentJobLocation = $this->Schools->find()->contain(['Cities'])->where(['Schools.id'=>$jobsDetail->school_id]);
        $currentJobProvince = $this->Provinces->find()->where(['id'=>$currentJobLocation->first()->city->province_id]);

        $currentCityList = $this->Cities->find()->where(['province_id'=>$currentJobLocation->first()->city->province_id]);

        $name = isset($currentJobLocation->first()->city->name) ? $currentJobLocation->first()->city->name : '招聘';
        $this->set('title',$name. '招聘_教师招聘网');
        $this->set('keywords',$name. ','.$name.'招聘');
        $this->set('description','招聘'.$name.',更多'.$name.'招聘信息可以查看职位信息、职位描述及具体工作内容说明，也可查看公司其他职位。');
        $this->set(compact('jobsDetail','inSameSchoolJob','currentJobLocation','currentJobProvince','currentCityList'));
    }

    /**
     * 找学校 detail
     */
    public function schoolDetail(){
        $id = $this->request->getParam('id');
        $schoolDetail = $this->Schools->find()->where(['id'=>$id])->contain(['Jobs']);
        if (!$schoolDetail){
            throw new NotFoundException(404);
        }

        $jobsCate = $this->getJobCate($schoolDetail->first()->jobs);
        $name = isset($schoolDetail->first()->title) ? $schoolDetail->first()->title : '学校详情';
        $this->set('title',$name.'招聘_教师招聘网');
        $this->set('keywords',$name.','.$name.'招聘');
        $this->set('description','教师招聘网为求职者提供2017年'.$name.'招聘信息，更有'.$name.'简介、学校地址及招聘职位等信息。');
        $this->set(compact('schoolDetail','jobsCate'));
    }

    /**
     * 指定显示分6个分类
     */
    public function assignCate(){
        $res = $this->SiteTdk->gettdk('assignCate');
        $this->set('title',$res['title']);
        $this->set('keywords',$res['keywords']);
        $this->set('description',$res['description']);

        $provinceName = $this->request->getData('filterName');

        $assignCate = explode('/',$this->request->url)[1];
        $page = $this->request->getParam('page',1);

        $this->paginate = [
            'limit'=>20,
            'page'=>$page
        ];

        $cateId = $this->Categories->find()->where(['name_py'=>$assignCate]);
        $query = $this->Jobs->find()->contain(['Categories', 'Schools'])->where(['Jobs.category_id'=>$cateId->first()->id]);
        $jobsList = $this->paginate($query);

        if(!$provinceName) {
            $provinceList = $this->Provinces->find();
        } else {
            $provinceList = $this->Provinces->find();
            $provinceList = $this->Cities->find()->where(['province_id'=>$provinceList->first()->id]);
        }

        $this->set(compact('jobsList'));
        $this->set(compact('provinceList'));
        $this->set(compact('cateId'));
        $this->set(compact('page'));
    }

    /**
     * 获取所有的 工作分类
     * @return \Cake\ORM\Query
     */
    public function getAllJobsCate(){
        return $this->Categories->find();
    }

    /**
     * 获取所有的 jobs 分类
     * @param $ids
     * @return array
     */
    public function getJobCate($ids){
        $result = [];
        foreach ($ids as $item) {
            $cate = $this->Categories->get($item->category_id);
            $result[$item->id] = $cate;
        }
        return $result;
    }

    /**
     * 根据学校list 获取当前工作的分类数据
     * @param $school
     * @return array
     */
    public function getJobCateBySchool($school){
        $result = [];
        foreach ($school as $item) {
            foreach ($item->jobs as $value) {
                $cate = $this->Categories->get($value->category_id);
                $result[$item->id][$value->id] = $cate;
            }
        }
        return $result;
    }

    /**
     * 获取当前省份下的所有city id
     * @param $provinceId
     * @return array
     */
    public function getCurrentCityId($provinceId){
        $result = [];
        $cityList = $this->Cities->find()->where(['province_id'=>$provinceId]);
        foreach ($cityList as $item){
            $result[] = $item->id;
        }
        return $result;
    }

    /**
     * 根据已经获取的cityId 获取所有的school id
     * @param $cityIds
     * @return array
     */
    public function getSchoolIds($cityIds){
        $result = [];
        $schoolList = $this->Schools->find()->where(['city_id in'=>$cityIds]);
        foreach ($schoolList as $item) {
            $result[] = $item->id;
        }
        return $result;
    }

    /**
     * 首页显示的内容，根据cate id 和城市ids 筛选数据
     * @param $cateId
     * @param bool $cityIds
     * @return $this|string
     */
    public function filterContentByCate($cateId,$cityIds = false){



        if($cityIds) {
            $response = $this->Jobs
                ->find()
                ->where([
                    'category_id'=>$cateId,
                    'city_id in'=>$this->getCityIds()
                ])
                ->contain(['Categories', 'Schools'])
                ->limit(10);
        } else {
            $response = $this->Jobs
                ->find()
                ->where([
                    'category_id'=>$cateId
                ])
                ->contain(['Categories', 'Schools'])
                ->limit(10);
        }
        return $response;
    }

    /**
     * 获取需要的城市id
     * @return $this|array
     */
    public function getCityIds(){
        $provinceId = $this->Provinces->find()->where(['name'=>$_COOKIE['city']]);//获取省份id
        if($provinceId->count()>0) {
            $cityIds = $this->getCurrentCityId($provinceId->first()->id); // 获取当前省份下的所有的cityId
        } else {
            $cityIds = $this->Cities->find()->where(['name'=>$_COOKIE['city']]);
            $cityIds = [$cityIds->first()->id];
        }
        return $cityIds;
    }
}
